package com.fc.h5dispaly.h5display.viewpager;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;

import java.lang.reflect.Field;


/**
 * Created by fc on 2020/5/13
 * Describe:
 *
 * @author fc
 */
public class RotationView extends FrameLayout implements IRotationView {
    private ViewPager viewPager;
    private CustomSpeedScroller scroller;
    private int mPageIndex;

    public RotationView(@NonNull Context context) {
        super(context);
        initView(context);
    }

    private void initView(Context context) {
        viewPager = new ViewPager(context);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        addView(viewPager, params);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mPageIndex = position;
                Log.d("0513", "onPageSelected: " + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void setData(int[] imgs) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getContext(), imgs);
        viewPager.setAdapter(adapter);
        viewPager.setPageTransformer(true, new CustomTransformer());
//        adapter.notifyDataSetChanged();
    }

    @Override
    public void setDuration(int duration) {
        try {
            // 通过class文件获取mScroller属性
            Field mField = ViewPager.class.getDeclaredField("mScroller");
            mField.setAccessible(true);
            mField.set(viewPager, scroller);

            scroller.setDuration(duration);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setInterpolator(Interpolator interpolator) {
        scroller = new CustomSpeedScroller(viewPager.getContext(), interpolator);
    }

    @Override
    public int getCurPageIndex() {
        return mPageIndex;
    }

    @Override
    public void nextPage() {
        viewPager.arrowScroll(2);
    }

    @Override
    public void prevPage() {
        viewPager.arrowScroll(1);
    }
}
